<!--
 * @Description: 新建 STR
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-08-05 11:01:39
 * @LastEditTime: 2021-10-26 16:57:25
 * @LastEditors: 0001100986/LiuShuai
-->
<template>
  <el-dialog
    :title="dialogTitle"
    :close-on-click-modal="false"
    width="500px"
    :visible.sync="dialogStatus"
    @close="cancel"
  >
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px" label-position="right">
      <!-- 名称 -->
      <el-form-item label="名称" prop="displayName">
        <el-input v-model="form.displayName" maxlength="100"></el-input>
      </el-form-item>
      <!-- 应用 -->
      <el-form-item label="应用" prop="aclName">
        <el-select
          v-model="form.aclName"
          clearable
          @clear="filterVmModel"
          placeholder="请选择应用"
          filterable
          v-el-select-loadmore="loadmore"
          :filter-method="filterVmModel"
          style="width: 100%;"
        >
          <el-option
            v-for="(item, index) in appList"
            :key="index"
            :value="item.applicationType === 'Acl' ? item.aclName :item.displayName"
            :label="item.displayName"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 优先级 -->
      <el-form-item label="高优先级" prop="hightLink">
        <el-select v-model="form.hightLink" style="width:100%;" @change="handleHight">
          <el-option
            v-for="(item, index) in ne.extAttrs.links"
            :key="index"
            :value="item.id"
            :label="item.userlabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 优先级 -->
      <el-form-item label="策略" prop="hightSamgr" v-show="form.hightLink">
        <el-select v-model="form.hightSamgr" style="width:100%;">
          <el-option
            v-for="(item, index) in hightSamgrList"
            :key="index"
            :value="item.id"
            :label="item.userlabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 低优先级 -->
      <el-form-item label="低优先级" prop="lowLink" v-show="form.hightLink">
        <el-select v-model="form.lowLink" style="width:100%;" clearable @change="handleLow">
          <el-option
            v-for="(item, index) in ne.extAttrs.links"
            :key="index"
            :value="item.id"
            :label="item.userlabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 策略 -->
      <el-form-item label="策略" prop="lowSamgr" v-show="form.lowLink">
        <el-select v-model="form.lowSamgr" style="width:100%;">
          <el-option
            v-for="(item, index) in lowSamgrList"
            :key="index"
            :value="item.id"
            :label="item.userlabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          type="textarea"
          :rows="3"
          v-model="form.description"
          maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  directives: {
    // 计算是否滚动到最下面
    'el-select-loadmore': {
      bind (el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          // scrollHeight 获取元素内容高度(只读)
          // scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
          // clientHeight 读取元素的可见高度(只读)
          // 如果元素滚动到底, 下面等式返回true, 没有则返回false:
          const condition = Math.round(this.scrollHeight - this.scrollTop) <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      }
    }
  },
  props: ['ne', 'type', 'dialogStatus'],
  data () {
    return {
      dialogTitle: '',
      form: {
        displayName: null,
        aclName: null,
        hightLink: null,
        hightSamgr: null,
        lowLink: null,
        lowSamgr: null,
        description: null
      },
      appList: [],
      page: {
        page: 1,
        pageSize: 15,
        total: 0
      },
      rules: {
        displayName: [{
          required: true,
          message: '请填写名称',
          trigger: 'blur'
        }],
        aclName: [{
          required: true,
          message: '请选择应用',
          trigger: 'change'
        }]
      },
      hightSamgrList: [],
      lowSamgrList: []
    };
  },
  watch: {
    type: {
      immediate: true,
      handler (val) {
        let _this = this;
        if (val === 'create') {
          _this.dialogTitle = '新建STR';
          _this.form = {
            displayName: null,
            aclName: null,
            hightLink: null,
            hightSamgr: null,
            lowLink: null,
            lowSamgr: null,
            description: null
          };
        }
      }
    }
  },
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      let params = {
        keyword: "Acl",
        neId: _this.ne.id,
        limit: _this.page.pageSize,
        offset: (_this.page.page - 1) * _this.page.pageSize
      };
      _this.getAclList(params);
    });
  },
  methods: {
    // 分页方法 详见 directives
    loadmore (firstTag) {
      let _this = this;
      // 筛选时下拉不触发分页
      if (!_this.filterText) {
        if (!firstTag) {
          _this.page.page++;
        }
        let params = {
          keyword: "Acl",
          neId: _this.ne.id,
          limit: _this.page.pageSize,
          offset: (_this.page.page - 1) * _this.page.pageSize
        };
        _this.getAclList(params);
      }
    },
    //  获取应用
    getAclList (params) {
      let _this = this;
      _this.$http.post({
        url: '/api/sdwan/application/aclrule/query',
        data: params
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          _this.appList = resultBody.objects;
        }
      });
    },
    // 筛选方法
    filterVmModel (value) {
      let _this = this;
      _this.filterText = value;
      // 筛选数据，有值时清空选项并按照关键字搜索对应结果集合
      if (value) {
        _this.appList = [];
        _this.$nextTick(() => {
          _this.page = {
            page: 1,
            pageSize: 15,
            total: 0
          };
          let params = {
            keyword: "Acl",
            neId: _this.ne.id,
            limit: _this.page.pageSize,
            offset: (_this.page.page - 1) * _this.page.pageSize
          };
          _this.getAclList(params);
        });
      } else {
        // 空值时，触发重置
        this.appList = [];
        this.$nextTick(() => {
          _this.page = {
            page: 1,
            pageSize: 15,
            total: 0
          };
          let params = {
            keyword: "Acl",
            neId: _this.ne.id,
            limit: _this.page.pageSize,
            offset: (_this.page.page - 1) * _this.page.pageSize
          };
          _this.getAclList(params);
        });
      }
    },
    // 高优先级
    handleHight (val) {
      let _this = this;
      let arry = _this.ne.extAttrs.links;
      let obj = arry.find(item => {
        return item.id === val;
      });
      _this.form.heightName = obj.userlabel;
      _this.$http.get({
        url: '/api/sdwan/policy/getPolicyList/' + _this.ne.id + '/' + val
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          _this.form.hightSamgr = null;
          if (resultBody.length > 0) {
            _this.hightSamgrList = resultBody[0].samgrList;
          }
        }
      });
    },
    // 低优先级
    handleLow (val) {
      let _this = this;
      let arry = _this.ne.extAttrs.links;
      let obj = arry.find(item => {
        return item.id === val;
      });
      _this.form.lowName = obj.userlabel;
      _this.$http.get({
        url: '/api/sdwan/policy/getPolicyList/' + _this.ne.id + '/' + val
      }).then(res => {
        let { status, resultBody } = res;
        if (status === '0') {
          _this.form.lowSamgr = null;
          if (resultBody.length > 0) {
            _this.lowSamgrList = resultBody[0].samgrList;
          }
        }
      });
    },
    // // 选择应用 过滤aclname
    // changeApp (val) {
    //   let _this = this;
    // }
    // 取消
    cancel () {
      let _this = this;
      _this.$emit('handleDialog', false);
      _this.$refs['ruleForm'].resetFields();
    },
    // 确认
    onSubmit () {
      let _this = this;
      _this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (_this.form.hightLink || _this.form.lowLink) {
            if (_this.form.hightLink === _this.form.lowLink) {
              _this.$message.error('不能选择同一条隧道！');
            } else {
              let params = {
                neId: _this.ne.id,
                siteId: _this.ne.extAttrs.siteId,
                displayName: _this.form.displayName,
                aclName: _this.form.aclName,
                links: [],
                description: _this.form.description,
                type: 'AR'
              };
              // let acl = this.appList.find(item => {
              //   return item.aclName === _this.form.aclName;
              // });
              if (_this.form.hightLink) {
                params.links.push({
                  linkId: _this.form.hightLink,
                  linkName: _this.form.heightName,
                  samgrId: _this.form.hightSamgr
                });
              }
              if (_this.form.lowLink) {
                params.links.push({
                  linkId: _this.form.lowLink,
                  linkName: _this.form.lowName,
                  samgrId: _this.form.lowSamgr
                });
              }
              let acl = {};
              for (let i = 0; i < _this.appList.length; i++) {
                if (_this.appList[i].applicationType === 'Acl') {
                  // eslint-disable-next-line max-depth
                  if (_this.appList[i].aclName === _this.form.aclName) {
                    acl = _this.appList[i];
                  }
                } else {
                  // eslint-disable-next-line max-depth
                  if (_this.appList[i].displayName === _this.form.aclName) {
                    acl = _this.appList[i];
                  }
                }
              }
              params.ruleId = acl.ruleId;
              if (_this.type === 'create') {
                _this.$http.post({
                  url: '/api/sdwan/applicationroute/create',
                  data: params
                }).then(res => {
                  let { status } = res;
                  if (status === '0') {
                    _this.$message.success('创建成功！');
                    _this.$parent.reset();
                    _this.cancel();
                  }
                });
              }
            }
          } else {
            _this.$message.error('请至少选择一条隧道！');
          }
        } else {
          _this.$message.error('请检查必填项！');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.ip-mask {
  width: 100%;
  ::v-deep .el-input {
    float: left;
  }
  ::v-deep .el-input:first-child {
    width: 75%;
  }
  label {
    display: block;
    width: 5%;
    float: left;
    text-align: center;
  }
  ::v-deep .el-input:last-child {
    width: 20%;
    &::after {
      content: "";
      overflow: hidden;
      clear: both;
    }
  }
}
.ip-port-mask {
  width: 100%;
  ::v-deep .el-input {
    float: left;
  }
  ::v-deep .el-input:first-child {
    width: 50%;
  }
  label {
    display: block;
    width: 5%;
    float: left;
    text-align: center;
  }
  ::v-deep .el-input {
    width: 20%;
  }
  ::v-deep .el-input:last-child {
    width: 20%;
    &::after {
      content: "";
      overflow: hidden;
      clear: both;
    }
  }
}
</style>